<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * PHP versions 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 *
 * @category   db 
 * @package    DINAMIC
 * @author     Kanazawa Kazuyoshi <kazu.php@gmail.com>
 * @copyright   
 * @license     
 * @version    CVS: $Id: db.class.php 69 2008-02-17 10:22:54Z kazu.php $
 * @link       
 * @see        
 * @since      
 * @deprecated 
 */


/**
 *
 * PHP versions 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   db 
 * @package    DINAMIC
 * @author     Kanazawa Kazuyoshi <kazu.php@gmail.com>
 * @copyright   
 * @license     
 * @version    CVS: $Id: db.class.php 69 2008-02-17 10:22:54Z kazu.php $
 * @link       
 * @see        
 * @since      
 * @deprecated 
 */

// {{{ class db 
class db 
{

    // {{{ properties

    private 
    $_dns = null,
    $_connection = null,
    $_user = null,
    $_host = null,
    $_password = null,
    $_database = null,
    $_tablename = null,
    $_dns_params = array(
            'user', 
            'password', 
            'host', 
            'database', 
            'tablename'
            ),
    $_colors = array('lightgray', 'whitesmoke');

    const SQL_QUERY_INSERT = 'INSERT INTO %s (%s) VALUES (%s)';
    const SQL_QUERY_UPDATE = '';
    const SQL_QUERY_SELECT = 'SELECT %s from %s';
    const SQL_SELECT_ALL = '*';
    const SQL_QUERY_DELETE = 'DELETE FROM %s';
    const SQL_QUERY_WHERE = 'WHERE %s = %s';
    const SQL_QUERY_VALUE_QUOTES = '\'%s\'';

    // see $this->columns();
    const COL_NAME          = 'Field';
    const COL_TYPE          = 'Type';
    const COL_NULL          = 'Null';
    const COL_KEY           = 'Key';
    const COL_DEFAULT       = 'Default';
    const COL_EXTRA         = 'Extra';
    const COL_ALL           = 'ALL';
    const COL_LENGTH        = 'LENGTH';

    const EXTRA_NUMBER      = '_num';
    const EXTRA_COLOR       = '_color';

    const ERROR_COLUMN_COUNT_MISMATCH = " 

        Error!! Field count do not match!
        cannot proceed with insertion 

        %s
        %s

        ";

    const ERROR_COLUMN_DOES_NOT_EXIST = "
        Error !! Column was not found in db-table

        Column      : %s
        Table       : %s
        
        ";

    // }}}

    // {{{ __construct
    public function __construct(
        $x = "x,x,x,x,x"
    )
    {
        $this->_dns = $dns;
        $array = $this->parse();
        foreach ($this->_dns_params as $param) {
            $_param = '_' . $param;
            $this->$_param = $array[$param];
        }
        $this->connect();
        $this->execute();
    }

    // }}}
    // {{{ currentDatabase

    public function currentDatabase()
    {
        return $this->_database;
    }

    // }}}
    // {{{ setColors

    public function setColors($array)
    {
        if (is_array($array)) {
            $this->_colors = $array;
        }
    }

    // }}}
    // {{{ execute

    public function execute()
    {
    }

    // }}}
    // {{{ populate

    public function populate($limit)
    {
        $result = 0; 
        $ret = $this->testRecord($limit);
        foreach ($ret as $array ) {
            $result = $result + $this->query($this->insertQuery($array));
        }
        return $result;
    }

    // }}}
    // {{{ parse

    private function parse()
    {
        $array = split(',', $this->_dns);
        $ret_array = array();
        $count = 0;
        
        if ((count($array) > 1)) {
            foreach ($array as $value){
                if (!empty($value)) {
                    $ret_array[$this->_dns_params[$count]] = $value;
                }
                $count ++;
            }
        }
        if (count($ret_array) > 3) {
            return $ret_array;
        }
    }

    // }}}
    // {{{ connect

    private function connect()
    {
        $this->_connection = mysql_pconnect(
            $this->_host, $this->_user, $this->_password
        );
        mysql_select_db($this->_database);
    }

    // }}}
    // {{{ disconect

    private function disconect()
    {
        $this->_connection = null;
    }

    // }}}
    // {{{ connection

    private function connection()
    {
        return $this->_connection;
    }

    // }}}
    // {{{ query

    public function query($query, $type = MYSQL_ASSOC)
    {
        $data = mysql_query($query, $this->_connection);
        $result = array();
        $count = 1;
        if (!is_resource($data)) {
            return $data;
        }
        while($ret = mysql_fetch_array($data, $type)) {
            $result[] = $ret;
            if (!array_key_exists(self::EXTRA_NUMBER, $result)) {
                $result[$count-1][self::EXTRA_NUMBER] = $count;
                if(!array_key_exists(self::EXTRA_COLOR, $result)) {
                    $val = next($this->_colors);
                    if ($val === false) {
                        reset($this->_colors);
                        $val = current($this->_colors);
                    }
                    $result[$count-1][self::EXTRA_COLOR] = $val; 
                }
                $count ++;
            }
        }
        if ($result == NULL) {
            return array();
        }
        return $result;
    }

    // }}}
    // {{{ columns

    public function columns($grab = self::COL_ALL)
    {
        $array = $this->query("DESC " . $this->_tablename);
        if ($grab == self::COL_ALL) {
            return $array;
        }

        $return_array = array();
        foreach ($array as $key => $subarray) {
            foreach ($subarray as $sub_key => $subvalue) {
                if ($sub_key == $grab) {
                    $return_array[] = $subvalue;
                } elseif (
                           ($grab == self::COL_LENGTH) 
                        && ($sub_key == self::COL_TYPE)) {
                    $return_array[] = preg_replace('/\D/', '', $subvalue);
                }
            }
        }
        unset($array);
        return $return_array;
    }

    // }}}
    // {{{ changeDatabase

    public function changeDatabase($database_name)
    {
        return mysql_select_db($database_name);
    }

    // }}}
    // {{{ changeTablename

    public function changeTablename($tablename)
    {
        $this->_tablename = $tablename;
    }

    // }}}
    // {{{ databases

    public function databases()
    {
        return $this->query("show databases");
    }

    // }}}
    // {{{ tables

    public function tables()
    {
        $return_array = array();
        $tables = $this->query("show tables");
        $suffix = 'Tables_in_';
        foreach ($tables as $value) {
            $key = $suffix . $this->currentDatabase();
            if ($value[$key]) {
                $ret_array[] = $value[$key];
            }
        }
        return $ret_array;
    }

    // }}}
    // {{{ updateQuery

    public function updateQuery()
    {
    }

    // }}}
    // {{{ canInsert

    public function canInsert($values, $omit = array())
    {
        return (count($values) == ($this->countColumns() - count($omit)));
    }

    // }}}
    // {{{ insertQuery

    public function insertQuery($values, $omit = array())
    {
        $splitter = ', ';
        return sprintf(
            self::SQL_QUERY_INSERT, 
            $this->_tablename,
            join($splitter, $this->columns(self::COL_NAME)),
            join($splitter, $values)
        );
    }

    // }}}
    // {{{ deleteQuery

    public function deleteQuery()
    {
        return sprintf(self::SQL_QUERY_DELETE, $this->_tablename);
    }

    // }}}
    // {{{ countColumns

    public function countColumns()
    {
        return count($this->columns());
    }

    // }}}
    // {{{ timestamp

    public function timestamp()
    {
        return microtime();
    }

    // }}}
    // {{{ today

    public function today()
    {
        return array(
            'year' => date('Y'),
            'month' => date('m'),
            'day' => date('d'),
            'hour' => date('h'),
            'minute' => date('i'),
            'second' => date('s')
        );
    }

    // }}}
    // {{{ records

    public function records($fields = self::SQL_SELECT_ALL)
    {
        return $this->query(
            sprintf(self::SQL_QUERY_SELECT, $fields, $this->_tablename)
        );
    }

    // }}}
    // {{{ columnLength

    private function columnLength($colname)
    {
        $array = $this->column($colname);
        return preg_replace('/\D/', '', $array[self::COL_TYPE]);
    }

    // }}}
    // {{{ column

    public function column($name)
    {
        $array = $this->columns();
        foreach ($array as $record) {
            if ($record[self::COL_NAME] == $name) {
                return $record;
            }
        }
        throw new exception(
            sprintf(
                self::ERROR_COLUMN_DOES_NOT_EXIST, 
                $name,
                $this->_tablename
            )
        );
    }

    // }}}
    // {{{ testRecord

    /**
     */
    public function testRecord($limit)
    {
        $array = $this->columns();
        $return_array = array();
        for ($i = 0; $i < $limit; $i ++) {
            $values = array();
            foreach ($array as $key => $record) {
                foreach ($record as $fieldname => $fieldvalue) {

                    $col_len = $this->columnLength(
                        $record[self::COL_NAME]
                    );

                    if ($fieldname == self::COL_TYPE) {
                        if (preg_match('/varchar/', $fieldvalue)) {
                            $values[] = sprintf(
                                self::SQL_QUERY_VALUE_QUOTES,
                                $this->generateString($col_len)
                            );
             //         } elseif (preg_match('/date/', $fieldvalue)) {
             //             $values[] = $this->timestamp();
                        } else {
                            $values[] = $this->generateNumber($col_len);
                        }
                    }
                }
            }
            $return_array[] = $values;
        }
        return $return_array;
    }

    // }}}
    // {{{ generateNumber

    public function generateNumber($limit)
    {
        $number = (String) rand(0, $limit);
        $number = '';
        while (strlen($number) < $limit) {
            $number .= rand(0, 9);
        }
        return $number;
    }

    // }}}
    // {{{ generateString

    public function generateString($strlen)
    {
        return uniqid();
    }

    // }}}

}

// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */

?>
